package com.szzg10.webservice.chapter3;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.xml.namespace.QName;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class ValidatorHandler implements SOAPHandler<SOAPMessageContext> {

	private static final int UUIDvariant = 2;
	private static final int UUIDversion = 4;
	
	@Override
	public boolean handleMessage(SOAPMessageContext ctx) {
		
		Boolean request_flag = (Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		
		if(!request_flag) {
			SOAPMessage message = ctx.getMessage();
			
			try {
				SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
				
				SOAPHeader header = envelope.getHeader();
				if(header == null) {
					generateSOAPFault(message, "No message header.");
				}
				
				Iterator iterator = header.extractAllHeaderElements();
				if(iterator == null || !iterator.hasNext()) {
					generateSOAPFault(message, "No header block for next actor.");
				}
				
				Node node = (Node)iterator.next();
				String value = node != null ? node.getValue() : null;
				if(value == null) {
					generateSOAPFault(message, "No UUID in header block.");
				}
				
				UUID uuid = UUID.fromString(value);
				if(uuid.variant() != UUIDvariant || uuid.variant() != UUIDversion) {
					generateSOAPFault(message, "Bad UUID variant or version.");
				}
				
				message.writeTo(System.out);
				
			} catch (SOAPException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return true;
	}
	
	@Override
	public void close(MessageContext arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean handleFault(SOAPMessageContext arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void generateSOAPFault(SOAPMessage msg, String reason) {
		
		try {
			SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
			SOAPFault fault = body.addFault();
			fault.setFaultString(reason);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
	}

}
